#    Copyright 2008, 2009 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPGIS.
#    COOPGIS is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPGIS is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPGIS.  If not, see <http://www.gnu.org/licenses/>.

import os
import datetime
FTPFileName='/opt/coopgis/fromgps/anonymousftproot_OtherReadOnly/incomingftpallpermissions/Locations.csv'
import shutil

#************************BEGIN Add Include Files to Path************************
import sys
NeededPaths=['/opt/coopgis/djangoproject/include', '/opt/coopgis/djangoproject']
for path in NeededPaths:
    if(not path in sys.path):
        sys.path.append(path)
#************************END   Add Include Files to Path************************
from django.contrib.gis.geos import *
import os, time, psycopg2, datetime
#********************Setup psycopg2 and django section********************
PathDjangoRoot="/opt/coopgis/"
if(not PathDjangoRoot in sys.path):
    sys.path.append(PathDjangoRoot)
import djangoproject
from djangoproject import settings

from djangoproject.models import *
#********************Setup psycopg2 and django section********************

from django.template import Context, loader
from django.http import HttpResponse
from django import forms
import os
import datetime
import djangoproject.settings

def GetOpenLayersZoom(station=None, span=None, Zoom=23, point=None, SRID=3857):
    """StakerAssemblyEditor.py (View) uses a custom zoom level for zooming in to the area covered by a Staker Work Order when no station or span is selected.
      All Other modules use the default zoom level."""
    if(point):
        point=point.transform(SRID, clone=True) 
        return "map.setCenter(new OpenLayers.LonLat(" + str(point.x) + ',' + str(point.y)  + "), " + str(Zoom) + ");" #Zoom into the point of the Station
    if(station):
        point=station.Point.transform(SRID, clone=True)
        return "map.setCenter(new OpenLayers.LonLat(" + str(point.x) + ',' + str(point.y)  + "), " + str(Zoom) + ");" #Zoom into the point of the Station
    elif(span):
        PointCoordinates=span.Line[0]
        point=Point(x=PointCoordinates[0], y=PointCoordinates[1])
        point.srid=span.Line.srid
        point=point.transform(SRID, clone=True)
        return "map.setCenter(new OpenLayers.LonLat(" + str(point.x) +',' + str(point.y)  + "), " + str(Zoom) + ");" #Zoom into the point of the Station
    else:
        return "map.setCenter(new OpenLayers.LonLat" + str(COOPGISConfig.GetDefaultCenter()) + ", " + str(Zoom) + ");"


def GetLatitudeLongitude(station=None, span=None, point=None, SRID=3857):
    if(point):
        point=point.transform(SRID, clone=True) 
        return point.x, point.y
    if(station):
        point=station.Point.transform(SRID, clone=True)
        return point.x, point.y
    elif(span):
        PointCoordinates=span.Line[0]
        point=Point(x=PointCoordinates[0], y=PointCoordinates[1])
        point.srid=span.Line.srid
        point=point.transform(SRID, clone=True)
        return point.x, point.y
    else:
        point=Station.objects.all()[0].Point.transform(SRID, clone=True)
        return point.x, point.y

def GetOpenLayersJavaScriptHeading():
    import urllib2
    URL = 'http://maps.google.com/maps/api/js?v=3.2&sensor=false'
    try:
        if(djangoproject.settings.COOPGISInVirtualMachineIndicator):
            raise(Exception('InVirtualMachine'))
        fileHandle = urllib2.urlopen(URL, None, 5)
        TestPageAccess = fileHandle.read()
        fileHandle.close()
    except:   #IOError
        TestPageAccess = False
    if(TestPageAccess):
        return """<script src="/openlayers/lib/OpenLayers.js"></script>
        <script src="http://maps.google.com/maps/api/js?v=3.2&sensor=false"></script>"""
    else:
        return """<script src="/openlayers/lib/OpenLayers.js"></script>"""
        

def GetOpenLayersJavaScriptSerializeFunction(FormFieldName=''):
    if not FormFieldName:
        return ''
    FunctionString="""
    function serialize(feature){
            var type = new OpenLayers.Format.WKT();
            var str = type.write(feature);
            // not a good idea in general, just for this demo
            str = str.replace(/,/g, ', ');
            document.getElementById(\"{{FormFieldName}}\").value = str;     
    }
    """.replace('{{FormFieldName}}', FormFieldName)
    return FunctionString


def GetOpenLayersJavaScriptPolygonFeature():
    return """
    var polygonLayer = new OpenLayers.Layer.Vector("Polygon Layer", 
                  {'buffer':0, 
                   'sphericalMercator': 'true',
                  'projection': new OpenLayers.Projection("EPSG:3857"),
                   visibility: true,
                   isBaseLayer: false,
                   transparent: true});
    polygonLayer.onFeatureInsert = serialize;
    map.addLayers([polygonLayer]);
    var polygon = new OpenLayers.Control.DrawFeature(polygonLayer, OpenLayers.Handler.Polygon);
    map.addControl(polygon);
    polygon.activate();
    var wkt = new OpenLayers.Format.WKT()
    """

def GetOpenLayersJavaScriptLineFeature():
    return """
    var lineLayer = new OpenLayers.Layer.Vector("Line Layer", 
                  {'buffer':0, 
                   'sphericalMercator': 'true',
                  'projection': new OpenLayers.Projection("EPSG:3857"),
                   visibility: true,
                   isBaseLayer: false,
                   transparent: true});
    lineLayer.onFeatureInsert = serialize;
    map.addLayers([lineLayer]);
    var line = new OpenLayers.Control.DrawFeature(lineLayer, OpenLayers.Handler.Path);
    map.addControl(line);
    line.activate();
    var wkt = new OpenLayers.Format.WKT()
    """

def GetOpenLayersJavaScriptPointFeature():
    return """
    var pointLayer = new OpenLayers.Layer.Vector("Point Layer", 
                  {'buffer':0, 
                   'sphericalMercator': 'true',
                  'projection': new OpenLayers.Projection("EPSG:3857"),
                   visibility: true,
                   isBaseLayer: false,
                   transparent: true});
    pointLayer.onFeatureInsert = serialize;
    map.addLayers([pointLayer]);
    var point = new OpenLayers.Control.DrawFeature(pointLayer, OpenLayers.Handler.Point);
    map.addControl(point);
    point.activate();
    var wkt = new OpenLayers.Format.WKT()
    """


def GetOpenLayersJavaScript(OpenLayersZoom = '{{ OpenLayersZoom }}', MapFileName='{{ MapFileName }}', 
                            LayerName='{{ LayerName }}', OpenLayersJavaScriptHeading='', GeometryFeature = ''):
    if('maps.google.com' in OpenLayersJavaScriptHeading):
        PageLayers="""   var gsat = new OpenLayers.Layer.Google("Google Satellite", {type: google.maps.MapTypeId.SATELLITE, numZoomLevels: 22});
    var gmap = new OpenLayers.Layer.Google("Google Streets", {numZoomLevels: 22});
    var gphy = new OpenLayers.Layer.Google("Google Physical",{type: google.maps.MapTypeId.TERRAIN});
    var ghyb = new OpenLayers.Layer.Google("Google Hybrid",{type: google.maps.MapTypeId.HYBRID, numZoomLevels: 22});"""
        AddLayers=" map.addLayers([graphic, gsat, gmap, gphy, ghyb, emap]);"
        #AddLayers=" map.addLayers([gsat, gmap, gphy, ghyb, emap]);"

    else:
        PageLayers=""
        AddLayers=" map.addLayers([graphic, emap]);"
    if GeometryFeature:
        if GeometryFeature == 'Polygon':
            OpenLayersSerializeFunction = GetOpenLayersJavaScriptSerializeFunction(FormFieldName = 'id_WKTPolygon')
            OpenLayersWKTOutput = GetOpenLayersJavaScriptPolygonFeature()
        elif GeometryFeature == 'Line':
            OpenLayersSerializeFunction = GetOpenLayersJavaScriptSerializeFunction(FormFieldName = 'id_WKTLine')
            OpenLayersWKTOutput = GetOpenLayersJavaScriptLineFeature()
        elif GeometryFeature == 'Point':
            OpenLayersSerializeFunction = GetOpenLayersJavaScriptSerializeFunction(FormFieldName = 'id_WKTPoint')
            OpenLayersWKTOutput = GetOpenLayersJavaScriptPointFeature()
        else:
            raise Exception('Invalid Geometry Specified in View')
    else:
        OpenLayersWKTOutput = ""
        OpenLayersSerializeFunction = ""
    return str("""  <script defer="defer" type="text/javascript">
    var bnd = new OpenLayers.Bounds""" + str(COOPGISConfig.GetDefaultBounds()) + """; 
    var options = {projection: new OpenLayers.Projection("EPSG:3857"),
        displayProjection: new OpenLayers.Projection("EPSG:4326"),
        units: "m",
        numZoomLevels: 29,
        minResolution: 0.01,
        maxExtent: bnd,
        'tileSize': new OpenLayers.Size(1024,768),
        'buffer':0};
       
    var map = new OpenLayers.Map('map', options);

    {{OpenLayersWKTOutput}}
    {{OpenLayersSerializeFunction}}

    var emap = new OpenLayers.Layer.MapServer("{{LayerName}}", 
                  "/cgi-bin/mapserv.cgi?MAP={{MapFileName}}",
                  {Layers:"Station Zoomed In"},
		   {'buffer':0, 
                   'sphericalMercator': 'true',
                  'projection': new OpenLayers.Projection("EPSG:3857"),
                   visibility: true,
                   isBaseLayer: false,
                   transparent: true});\n""" + PageLayers + """ 
    var optionsforgraphic = {numZoomLevels: 29, maxResolution: 10000000, minResolution: 0.01};

    var graphic = new OpenLayers.Layer.Image('Background',
         '/mapbackground.png',
         bnd,
         new OpenLayers.Size(1024, 1024),
         optionsforgraphic);
    graphic.events.on({loadstart: function() {OpenLayers.Console.log("loadstart");},
                       loadend: function() {OpenLayers.Console.log("loadend");}});\n""" + AddLayers + """ 
    map.addControl(new OpenLayers.Control.ScaleLine());
    map.addControl(new OpenLayers.Control.LayerSwitcher());
    map.addControl(new OpenLayers.Control.Permalink());
    map.addControl(new OpenLayers.Control.MousePosition());
    if (!map.getCenter()) {map.zoomToExtent(bnd)}
	    {{ OpenLayersZoom }}

  </script>

   """).replace('{{ OpenLayersZoom }}', OpenLayersZoom).replace('{{MapFileName}}', MapFileName).replace(
                '{{LayerName}}', LayerName).replace('{{OpenLayersWKTOutput}}', OpenLayersWKTOutput).replace(
                '{{OpenLayersSerializeFunction}}', OpenLayersSerializeFunction)
